package com.yzt.dynamicmodule.fragment

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.location.LocationManager
import android.os.Handler
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.annotation.Keep
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.yzt.dynamicmodule.R
import com.yzt.p_base.utils.ToastUtil
import com.yzt.zhuju.arouter.RouterSayu
import com.yzt.zhuju.base.BaseFragment
import com.yzt.zhuju.event.RxBus
import com.yzt.zhuju.event.main.IndexLocalEvent
import com.yzt.zhuju.event.user.GameAddEvent
import com.yzt.zhuju.utils.FastClickUtils
import com.yzt.zhuju.utils.map.BdLocationUtil
import com.zaaach.citypicker.CityPicker
import com.zaaach.citypicker.adapter.OnPickListener
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.model.LocateState
import com.zaaach.citypicker.model.LocatedCity

/**
 * author : bob
 * date   : 2022/11/15
 * desc   : 首页模块
 */

@Keep
@Route(path = RouterSayu.FRAGMENT_INDEX_MAIN)
class IndexMainFragment : BaseFragment() {

    private val MY_PERMISSIONS_REQUEST_LOCATION = 9999

    private var mTabLayout: TabLayout? = null
    private var mViewPager: ViewPager2? = null
    private var tvCity: TextView? = null

    private lateinit var mDynamicPageChangeCallback: IndexPageChangeCallback
    private lateinit var mTabLayoutMediator: TabLayoutMediator

    override fun getLayoutId(): Int {
        return R.layout.fragment_index
    }

    override fun installViews() {
        mTabLayout = findViewById(R.id.index_tab_room)
        mViewPager = findViewById(R.id.viewPager)
        initViews()
    }

    override fun netWorkRequest() {}

    /**
     * 加载页面分类
     */
    private fun initViews() {
        val tabs: MutableList<String> = ArrayList()
        tabs.add("推荐")
        tabs.add("关注")
        tabs.add("动态")
        mViewPager!!.adapter = object : FragmentStateAdapter(this@IndexMainFragment) {
            override fun getItemCount(): Int {
                return tabs.size
            }

            override fun createFragment(position: Int): Fragment {
                return when (position) {
                    0 -> IndexDiscoverFragment.getInstance(1)
                    1 -> IndexDiscoverFragment.getInstance(2)
                    else -> {
                        IndexDiscoverFragment.getInstance(3)
                    }
                }
            }
        }

        mTabLayoutMediator = TabLayoutMediator(mTabLayout!!, mViewPager!!) { tab, position ->
            TextView(mActivity).apply {
                gravity = Gravity.CENTER
                text = tabs[position]
                textSize = 16f
                typeface = Typeface.DEFAULT
            }.also {
                tab.customView = it
            }
        }
        mTabLayoutMediator.attach()
        mDynamicPageChangeCallback = IndexPageChangeCallback()
        mViewPager!!.registerOnPageChangeCallback(mDynamicPageChangeCallback)
        tvCity = findViewById(R.id.tv_city)
        tvCity!!.setOnClickListener(this)
        initPermission()

        // 发布游戏成功
        observerRxBus(GameAddEvent::class.java) { event: GameAddEvent? ->
            mViewPager!!.currentItem = 0
        }
    }

    /**
     * 权限初始化
     */
    private fun initPermission() {
        if (ContextCompat.checkSelfPermission(
                mActivity,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity, Manifest.permission.ACCESS_FINE_LOCATION
                )
            ) {
                // 方法帮助应用判断是否需要向用户解释为什么需要某个权限，并在适当的时候进行解释和再次请求。
            } else {
                //请求权限
                ActivityCompat.requestPermissions(
                    mActivity,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    MY_PERMISSIONS_REQUEST_LOCATION
                )
            }
        } else {
            // 权限满足
            initLocationOption()
        }
    }

    /**
     * 获取定位信息
     */
    private fun initLocationOption() {
        if (!checkGPSIsOpen(mActivity)) {
            ToastUtil.showMessage("请打开GPS定位服务")
        }
        BdLocationUtil.getInstance().requestLocation { location ->
            val latLng = BdLocationUtil.bd2gd(location.latitude, location.longitude)
            tvCity!!.text = location.city
            RxBus.getDefault().post(
                IndexLocalEvent(
                    location.cityCode, latLng.latitude.toString(), latLng.longitude.toString()
                )
            )
        }
    }

    private inner class IndexPageChangeCallback : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)

            val tabCount = mTabLayout!!.tabCount
            for (index in 0..tabCount) {
                val tab = mTabLayout!!.getTabAt(index)
                val tabView = tab?.customView as? TextView
                tabView?.let {
                    if (tab.position == position) {
                        it.textSize = 18f
                        it.setTextColor(
                            ContextCompat.getColor(
                                mActivity, R.color.white
                            )
                        )
                        it.typeface = Typeface.DEFAULT
                    } else {
                        it.setTextColor(
                            ContextCompat.getColor(
                                mActivity, R.color.text_c1
                            )
                        )
                        tabView.textSize = 18f
                        it.typeface = Typeface.DEFAULT
                    }
                }
            }
        }
    }

    override fun onClick(view: View) {
        super.onClick(view)
        if (FastClickUtils.isFastClick()) {
            return
        }
        if (view.id == R.id.tv_city) {
            // 城市选择
            CityPicker.from(activity).enableAnimation(true)
                .setAnimationStyle(R.style.DefaultCityPickerAnimation).setLocatedCity(null)
                .setOnPickListener(object : OnPickListener {
                    override fun onPick(position: Int, data: City) {
                        tvCity!!.text = data.name
                        BdLocationUtil.getInstance().cityChooseCode = data.code.toInt()
                        BdLocationUtil.getInstance().checkCity = data.name
                        BdLocationUtil.getInstance().requestLocation { location ->
                            val latLng = BdLocationUtil.bd2gd(location.latitude, location.longitude)
                            RxBus.getDefault().post(
                                IndexLocalEvent(
                                    data.code,
                                    latLng.latitude.toString(),
                                    latLng.longitude.toString()
                                )
                            )
                        }
                    }

                    override fun onCancel() {

                    }

                    override fun onLocate() {
                        //开始定位，这里模拟一下定位
                        Handler().postDelayed({
                            BdLocationUtil.getInstance().requestLocation { location ->
                                CityPicker.from(activity!!).locateComplete(
                                    LocatedCity(
                                        location.city, location.province, location.cityCode
                                    ), LocateState.SUCCESS
                                )
                            }
                        }, 2000)
                    }
                }).show()
        }
    }

    companion object {
        fun checkGPSIsOpen(context: Context): Boolean {
            val locationManager =
                context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            return gps || network
        }
    }
}